module Cip
  class Admin::CategoriesController < Admin::ApplicationController
    def show
      redirect_to edit_cip_admin_category_path(params[:id])
    end

    def new
      @category = Category.where(parent_id: params[:category_id]).new
    end

    def create
      @category = Category.where(parent_id: params[:category_id]).new(category_params)
      if @category.save
        redirect_to cip_admin_category_pages_path(@category)
      else
        render :new
      end
    end

    def edit
      @category = Category.find(params[:id])
    end

    def update
      @category = Category.find(params[:id])
      if @category.update_attributes(category_params)
        redirect_to cip_admin_category_pages_path(@category)
      else
        render :edit
      end
    end

    def destroy
      @category = Category.find(params[:id])
      @category.destroy
      redirect_to cip_admin_category_pages_path(@category.parent)
    end

    private

    def category_params
      params.require(:cip_category).permit(:title, :avatar, :_destroy_avatar, :forwarding_type, :content, :forwarding_page_id, :forwarding_category_id, :forwarding_url, :slug, :position, :parent_id, :editable, :hidden, :template, :hint, :page_template, :page_hint, :children_hint, :unparsed_page_metadata_struct, :unparsed_children_metadata_struct, :disabled).tap do |whitelisted|
        if params[:cip_category][:metadata]
          whitelisted[:metadata] = params[:cip_category][:metadata].permit!
        end
      end
    end
  end
end
